package service.impl;

import common.consts.Consts;
import common.consts.YesNo;
import dao.AccountDao;
import dao.FavoriteDao;
import domain.Account;
import domain.Favorite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.FavoriteService;
import service.ServiceResponse;

import java.util.Date;

/**
 * Created by zf on 15/7/17.
 */


@Service
public class FavoriteServiceImpl extends ServiceBase implements FavoriteService {


    @Autowired
    private AccountDao accountDao;

    @Autowired
    private FavoriteDao favoriteDao;


    @Override
    @Transactional(readOnly = false)
    public ServiceResponse favorite(long userId, long favorUserId) {

        Account user = accountDao.get(userId);
        if (user == null) {
            return ServiceResponse.fail(Consts.i18nKey.UNKNOWN_USER);
        }


        Account favoriteUser = accountDao.get(favorUserId);
        if (favoriteUser == null) {
            return ServiceResponse.fail(Consts.i18nKey.UNKNOWN_USER);
        }


        //根据userId和favorUserId  是否favorite表中存在记录
        Favorite favoring = favoriteDao.queryByUserIdAndFavorUserId(userId, favorUserId);
        Favorite favored;


        if (favoring != null) {
            /* userId已对favorUserId收藏 不影响任何数据现状 直接返回fail响应 */
            return ServiceResponse.fail(Consts.i18nKey.FAVORIED_ALREADY);

        } else {
            /* userId未对favorUserId收藏 执行收藏动作 返回success响应 */
            favoring = new Favorite(userId, favorUserId, new Date(), YesNo.No.charVal);

            favored = favoriteDao.queryByUserIdAndFavorUserId(favorUserId, userId);
            if (favored != null) {
                /* 此时双向收藏 */
                favoring.setOvonic(YesNo.Yes.charVal);
                favored.setOvonic(YesNo.Yes.charVal);
                favoriteDao.updateOvonic(favored.getId(), favored.getOvonic());
            }

            favoriteDao.insert(favoring);

            return ServiceResponse.success();

        }
    }
}
